package com.geek.factory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.factory.entity.*;
import com.geek.factory.mapper.ContractUserMapper;
import com.geek.factory.mapper.TContractMapper;
import com.geek.factory.service.TContractService;
import com.geek.factory.utils.POIUtils;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-21
 */
@Service
public class TContractServiceImpl extends ServiceImpl<TContractMapper, TContract> implements TContractService {
    @Autowired
    private ContractUserMapper contractUserMapper;
    //添加检查组
    @Transactional
    @Override
    public boolean save(Integer[] UserIds, TContract tContract) {
        //1.先插入检查组
        int i = baseMapper.insert(tContract);
        //2.再插入关系表
        insertContractUser(UserIds , tContract);
        return i>0?true:false;
    }

    private void insertContractUser(Integer[] UserIds, TContract tContract) {
        if (UserIds == null || UserIds.length == 0) return;
        Stream.of(UserIds).forEach(userId -> {
            ContractUser contractUser = new ContractUser();
            contractUser.setContractId(tContract.getId()); // 合同ID
            contractUser.setUserId(userId);                // 用户ID
            contractUserMapper.insert(contractUser);
        });
    }


    @Override
    public boolean upload(MultipartFile excelFile) throws IOException {
        if(excelFile != null) {
            // Read data from uploaded Excel file
            List<String[]> strings = POIUtils.readExcel(excelFile);

            // Convert List<String[]> to List<Contract>
            List<TContract> contracts = strings.stream().map(strs -> {
                TContract contract = new TContract();
                contract.setName(strs[0]);
                contract.setAmount(new BigDecimal(strs[1]));
                contract.setType(strs[2]);
                contract.setPartyA(strs[3]);
                contract.setPartyB(strs[4]);
                contract.setEffectiveTime(LocalDateTime.parse(strs[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                contract.setTerminationTime(LocalDateTime.parse(strs[6], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                contract.setPayWay(strs[7]);
                contract.setPayType(strs[8]);
                contract.setContractFile(strs[9]);
                contract.setStatus(Integer.parseInt(strs[10]));
                contract.setCreateTime(LocalDateTime.now());
                contract.setUpdateTime(LocalDateTime.now());
                return contract;
            }).collect(Collectors.toList());

            // Process each contract - insert or update
            contracts.forEach(this::editContract);
            return true;
        }
        return false;
    }

    private void editContract(TContract contract) {
        // Check if contract with same name exists
        LambdaQueryWrapper<TContract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TContract::getName, contract.getName());
        TContract existingContract = baseMapper.selectOne(wrapper);

        if(existingContract != null) {
            // Update existing contract
            contract.setId(existingContract.getId());
            contract.setCreateTime(existingContract.getCreateTime()); // Keep original create time
            baseMapper.updateById(contract);
        } else {
            // Insert new contract
            baseMapper.insert(contract);
        }
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // Set response headers
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=contract_template.xlsx");

        // Create Excel workbook
        XSSFWorkbook workbook = new XSSFWorkbook();
        // Create worksheet
        XSSFSheet sheet = workbook.createSheet("合同导入模板");

        // Create header row
        XSSFRow headerRow = sheet.createRow(0);
        String[] headers = {
                "合同名称",
                "合同金额",
                "合同类型",
                "甲方",
                "乙方",
                "生效时间(yyyy-MM-dd HH:mm:ss)",
                "终止时间(yyyy-MM-dd HH:mm:ss)",
                "支付方式",
                "支付类型",
                "合同文件路径",
                "合同状态(0:草稿,1:生效,2:终止,3:完成)"
        };

        for (int i = 0; i < headers.length; i++) {
            XSSFCell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create example data row
        XSSFRow dataRow = sheet.createRow(1);
        String[] example = {
                "羊村项目开发合同",
                "100000.00",
                "技术开发",
                "狼堡科技有限公司",
                "青青草原软件公司",
                "2023-01-01 00:00:00",
                "2023-12-31 23:59:59",
                "银行转账",
                "分期付款",
                "/contracts/xx_project.pdf",
                "1"
        };

        for (int i = 0; i < example.length; i++) {
            XSSFCell cell = dataRow.createCell(i);
            cell.setCellValue(example[i]);
        }

        // Auto-size columns
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write to response stream
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    @Override
    public void generatePdf(Integer contractId, HttpServletResponse response) throws Exception {
        TContract contract = this.getById(contractId);
        if (contract == null || contract.getContent() == null) {
            response.setContentType("application/json");
            response.getWriter().write("{\"msg\":\"合同不存在或无正文\"}");
            return;
        }
        String html = contract.getContent();
        // 可选：加上html头部，保证样式
        if (!html.trim().toLowerCase().startsWith("<html")) {
            html = "<html><head><meta charset='utf-8'></head><body>" + html + "</body></html>";
        }
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=contract_" + contractId + ".pdf");
        try (OutputStream os = response.getOutputStream()) {
            PdfRendererBuilder builder = new PdfRendererBuilder();
            builder.withHtmlContent(html, null);
            builder.toStream(os);
            builder.run();
        }
    }

}
